2013-03-03 17 views
1

是否可以通过它在我的url结尾检测到“.json”或“.xml”来设置路由? 而我怎么读,是否有可能不通过添加一个参数到我的操作方法读取该参数? 我宁愿不使用查询字符串来达到这个目的,它对我来说似乎很难看。如何检测ASP.NET MVC 4中的自定义URI?

MyWebsite/Controller/MyAction.json 

MyWebsite/Controller/MyAction.xml 

MyWebsite/Controller/MyAction.otherType 

--- 

public ActionResult MyAction() 
{ 
    var myData = myClient.GetData(); 
    return SerializedData(myData); 
} 

private ActionResult SerializedData(Object result) 
{ 
    String resultType = SomeHowGetResultTypeHere; 

    if (resultType == "json") 
    { 
     return Json(result, JsonRequestBehavior.AllowGet); 
    } 
    else if (resultType == "xml") 
    { 
     return new XmlSerializer(result.GetType()) 
      .Serialize(HttpContext.Response.Output, sports); 
    } 
    else 
    { 
     return new HttpNotFoundResult(); 
    } 
} 

回答

1

不是你问什么了,但它的工作原理。首先在你的路由配置添加此默认路由(重要)以上:

routes.MapRoute(
    name: "ContentNegotiation", 
    url: "{controller}/{action}.{contentType}", 
    defaults: new { controller = "Home", action = "MyAction", contentType = UrlParameter.Optional } 
); 

要处理点在你的网址,你需要修改Web.config文件部分system.webServer>处理程序中加入这一行:

<add name="ApiURIs-ISAPI-Integrated-4.0" path="/home/*" verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" /> 

这种新的处理器会用/开头家/ *所有的URL工作,但只要你喜欢,你可以chenge它。

比你contoroller:

public ActionResult MyAction(string contentType) 
{ 
    return SerializedData(new { id = 1, name = "test" }, contentType); 
} 

这种方法使用参数MyAction,但你可以这样调用:

MyWebsite/Controller/MyAction.json 

不喜欢这个

MyWebsite/Controller/MyAction?contentType=json 

是什么东西你问了。