1

Is it possible to set the routing in a way that it detects ".json" or ".xml" at the end of my url? And How would I read that, Is it possible not to read that parameter by adding a parameter to my action method? I rather not use a query string for this purpose, it just seems ugly to me.

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();
   }
}
aryaxt
  • 76,198
  • 92
  • 293
  • 442

1 Answers1

1

Not exactly what you asked for but it works... First in your routes config add this above Default route (important):

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

To handle dot in your URL you need to modify Web.config in section system.webServer > handlers add this line:

<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" />

this new handler will work for all urls with /home/* on the beginning but you can chenge it as you like.

Than in your contoroller:

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

This approach uses parameter for MyAction but you can call it like this:

MyWebsite/Controller/MyAction.json

not like this

MyWebsite/Controller/MyAction?contentType=json

What is something you asked for.

Łukasz Adamus
  • 266
  • 5
  • 19