如何在ASP中检测自定义URI.Net MVC 4
本文关键字:URI Net MVC 自定义 检测 ASP | 更新日期: 2023-09-27 18:02:04
是否可以将路由设置为它检测到的方式?Json"或"。xml"在我的url结束?我怎么读取呢,有没有可能不通过给动作方法添加参数来读取这个参数呢?我宁愿不使用查询字符串用于此目的,它对我来说似乎很丑。
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();
}
}
不完全是你要求的,但它的工作…首先,在你的路由配置中添加以下内容默认路由(重要):
routes.MapRoute(
name: "ContentNegotiation",
url: "{controller}/{action}.{contentType}",
defaults: new { controller = "Home", action = "MyAction", contentType = UrlParameter.Optional }
);
要处理URL中的点,您需要修改Web。在节系统中配置。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" />
这个新的处理程序将适用于所有以/home/*开头的url,但你可以根据自己的喜好更改它。
Than in your controller:
public ActionResult MyAction(string contentType)
{
return SerializedData(new { id = 1, name = "test" }, contentType);
}
这种方法使用MyAction的参数,但是你可以这样调用它:
MyWebsite/Controller/MyAction.json
not like this
MyWebsite/Controller/MyAction?contentType=json