I have searched and tried many localization approaches but all is not exactly what I want. Basically, I want to have my url like this
www.myweb.com <== default language (which is English)
www.myweb.com/promotion
www.myweb.com/th/promotion <== local language (Thai)
www.myweb.com/cn/promotion <== local language (Chinese)
Then I want these url to map with different View structure as below
/Views
/_Localization
/cn
/Home
/About.cshtml
/Index.cshtml
/Shared
/_Layout.cshtml
/Error.cshtml
/th
/Home
/About.cshtml
/Shared
/Home
/About.cshtml
/Index.cshtml
/Shared
/_Layout.cshtml
/_LogOnPartial.cshtml
/Error.cshtml
_ViewStart.cshtml
Web.config
As you can seen, Thai doesn't have it own Index.cshtml, _Layout.cshtml and Error.cshtml. So, I would like this to fallback to use the default instead. But chinese will use it own.
I have tried to MapRoute like this
routes.MapRoute(
"DefaultLocal",
"{lang}/{controller}/{action}/{id}",
new { lang = "th", controller = "Home", action = "Index", id = UrlParameter.Optional }
);
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
but I don't know how to point to different View structure. And in this example, Brian Reiter, it use Cookie not url.
So, how can I achieve this. note that I use RazorViewEngine.
Thank you for any help and thought.
Due to large amount of code needed i will only illustrate an idea of how it could be done.
You can subclass from RazorViewEngine like this:
public class I18NRazorViewEngine : RazorViewEngine
{
public I18NRazorViewEngine() : this(null)
{ }
protected string[] I18NAreaViewLocationFormats;
protected string[] I18NAreaMasterLocationFormats;
protected string[] I18NAreaPartialViewLocationFormats;
protected string[] I18NViewLocationFormats;
protected string[] I18NMasterLocationFormats;
protected string[] I18NPartialViewLocationFormats;
public I18NRazorViewEngine(IViewPageActivator viewPageActivator)
: base(viewPageActivator)
{
this.I18NAreaViewLocationFormats = new string[]
{
"~/Areas/{3}/{2}/Views/{1}/{0}.cshtml",
"~/Areas/{3}/{2}/Views/{1}/{0}.vbhtml",
"~/Areas/{3}/{2}/Views/Shared/{0}.cshtml",
"~/Areas/{3}/{2}/Views/Shared/{0}.vbhtml"
};
this.I18NAreaMasterLocationFormats = new string[]
{
"~/Areas/{3}/{2}/Views/{1}/{0}.cshtml",
"~/Areas/{3}/{2}/Views/{1}/{0}.vbhtml",
"~/Areas/{3}/{2}/Views/Shared/{0}.cshtml",
"~/Areas/{3}/{2}/Views/Shared/{0}.vbhtml"
};
this.I18NAreaPartialViewLocationFormats = new string[]
{
"~/Areas/{3}/{2}/Views/{1}/{0}.cshtml",
"~/Areas/{3}/{2}/Views/{1}/{0}.vbhtml",
"~/Areas/{3}/{2}/Views/Shared/{0}.cshtml",
"~/Areas/{3}/{2}/Views/Shared/{0}.vbhtml"
};
this.I18NViewLocationFormats = new string[]
{
"~/Views/{2}/{1}/{0}.cshtml",
"~/Views/{2}/{1}/{0}.vbhtml",
"~/Views/{2}/Shared/{0}.cshtml",
"~/Views/{2}/Shared/{0}.vbhtml"
};
this.I18NMasterLocationFormats = new string[]
{
"~/Views/{2}/{1}/{0}.cshtml",
"~/Views/{2}/{1}/{0}.vbhtml",
"~/Views/{2}/Shared/{0}.cshtml",
"~/Views/{2}/Shared/{0}.vbhtml"
};
this.I18NPartialViewLocationFormats = new string[]
{
"~/Views/{2}/{1}/{0}.cshtml",
"~/Views/{2}/{1}/{0}.vbhtml",
"~/Views/{2}/Shared/{0}.cshtml",
"~/Views/{2}/Shared/{0}.vbhtml"
};
}
public override ViewEngineResult FindView(ControllerContext controllerContext, string viewName, string masterName, bool useCache)
{
var langValue = controllerContext.Controller.ValueProvider.GetValue("lang");
if (langValue == null || String.IsNullOrEmpty(langValue.AttemptedValue))
return base.FindView(controllerContext, viewName, masterName, useCache);
//Code here
}
public override ViewEngineResult FindPartialView(ControllerContext controllerContext, string partialViewName, bool useCache)
{
var langValue = controllerContext.Controller.ValueProvider.GetValue("lang");
if (langValue == null || String.IsNullOrEmpty(langValue.AttemptedValue))
return base.FindPartialView(controllerContext, partialViewName, useCache);
//Code here
}
}
The next what you should do is to look inside VirtualPathProviderViewEngine on FindView and FindPartialView inplementations. The reflected code is like this:
public virtual ViewEngineResult FindPartialView(ControllerContext controllerContext, string partialViewName, bool useCache)
{
if (controllerContext == null)
{
throw new ArgumentNullException("controllerContext");
}
if (string.IsNullOrEmpty(partialViewName))
{
throw new ArgumentException(MvcResources.Common_NullOrEmpty, "partialViewName");
}
string requiredString = controllerContext.RouteData.GetRequiredString("controller");
string[] searchedLocations;
string path = this.GetPath(controllerContext, this.PartialViewLocationFormats, this.AreaPartialViewLocationFormats, "PartialViewLocationFormats", partialViewName, requiredString, "Partial", useCache, out searchedLocations);
if (string.IsNullOrEmpty(path))
{
return new ViewEngineResult(searchedLocations);
}
return new ViewEngineResult(this.CreatePartialView(controllerContext, path), this);
}
and
public virtual ViewEngineResult FindView(ControllerContext controllerContext, string viewName, string masterName, bool useCache)
{
if (controllerContext == null)
{
throw new ArgumentNullException("controllerContext");
}
if (string.IsNullOrEmpty(viewName))
{
throw new ArgumentException(MvcResources.Common_NullOrEmpty, "viewName");
}
string requiredString = controllerContext.RouteData.GetRequiredString("controller");
string[] first;
string path = this.GetPath(controllerContext, this.ViewLocationFormats, this.AreaViewLocationFormats, "ViewLocationFormats", viewName, requiredString, "View", useCache, out first);
string[] second;
string path2 = this.GetPath(controllerContext, this.MasterLocationFormats, this.AreaMasterLocationFormats, "MasterLocationFormats", masterName, requiredString, "Master", useCache, out second);
if (string.IsNullOrEmpty(path) || (string.IsNullOrEmpty(path2) && !string.IsNullOrEmpty(masterName)))
{
return new ViewEngineResult(first.Union(second));
}
return new ViewEngineResult(this.CreateView(controllerContext, path, path2), this);
}
both methods rely on private GetPath method:
private string GetPath(ControllerContext controllerContext, string[] locations, string[] areaLocations, string locationsPropertyName, string name, string controllerName, string cacheKeyPrefix, bool useCache, out string[] searchedLocations)
{
searchedLocations = VirtualPathProviderViewEngine._emptyLocations;
if (string.IsNullOrEmpty(name))
{
return string.Empty;
}
string areaName = AreaHelpers.GetAreaName(controllerContext.RouteData);
List<VirtualPathProviderViewEngine.ViewLocation> viewLocations = VirtualPathProviderViewEngine.GetViewLocations(locations, (!string.IsNullOrEmpty(areaName)) ? areaLocations : null);
if (viewLocations.Count == 0)
{
throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, MvcResources.Common_PropertyCannotBeNullOrEmpty, new object[]
{
locationsPropertyName
}));
}
bool flag = VirtualPathProviderViewEngine.IsSpecificPath(name);
string text = this.CreateCacheKey(cacheKeyPrefix, name, flag ? string.Empty : controllerName, areaName);
if (useCache)
{
return this.ViewLocationCache.GetViewLocation(controllerContext.HttpContext, text);
}
if (!flag)
{
return this.GetPathFromGeneralName(controllerContext, viewLocations, name, controllerName, areaName, text, ref searchedLocations);
}
return this.GetPathFromSpecificName(controllerContext, name, text, ref searchedLocations);
}
What you should do is to reimplement it. Most of the code you can reuse, but you should create your own method instead of VirtualPathProviderViewEngine.GetViewLocations. Here its reflected code:
private static List<VirtualPathProviderViewEngine.ViewLocation> GetViewLocations(string[] viewLocationFormats, string[] areaViewLocationFormats)
{
List<VirtualPathProviderViewEngine.ViewLocation> list = new List<VirtualPathProviderViewEngine.ViewLocation>();
if (areaViewLocationFormats != null)
{
for (int i = 0; i < areaViewLocationFormats.Length; i++)
{
string virtualPathFormatString = areaViewLocationFormats[i];
list.Add(new VirtualPathProviderViewEngine.AreaAwareViewLocation(virtualPathFormatString));
}
}
if (viewLocationFormats != null)
{
for (int j = 0; j < viewLocationFormats.Length; j++)
{
string virtualPathFormatString2 = viewLocationFormats[j];
list.Add(new VirtualPathProviderViewEngine.ViewLocation(virtualPathFormatString2));
}
}
return list;
}
You can also reuse most of the code but instead of VirtualPathProviderViewEngine.ViewLocation and VirtualPathProviderViewEngine.AreaAwareViewLocation you should use your own classes. They could be like this:
class ViewLocation
{
protected string _virtualPathFormatString;
public ViewLocation(string virtualPathFormatString)
{
this._virtualPathFormatString = virtualPathFormatString;
}
public virtual string Format(string viewName, string controllerName, string areaName, string lang)
{
return string.Format(CultureInfo.InvariantCulture, this._virtualPathFormatString, new object[]
{
viewName,
controllerName,
lang
});
}
}
and:
class AreaAwareViewLocation : VirtualPathProviderViewEngine.ViewLocation
{
public AreaAwareViewLocation(string virtualPathFormatString) : base(virtualPathFormatString)
{
}
public override string Format(string viewName, string controllerName, string areaName, string lang)
{
return string.Format(CultureInfo.InvariantCulture, this._virtualPathFormatString, new object[]
{
viewName,
controllerName,
areaName,
lang
});
}
}
and then when you will call Format methods you should pass langValue.AttemptedValue (it is from scope of FindView and FindPartialView in the first code block) to lang parameter. Normally it's called in VirtualPathProviderViewEngine.GetPathFromGeneralName.
The main advice is to use ILSpy or another disassembler to explore the code of System.Web.Mvc (or even better - download its sources). The goal is to reimplement FindView and FindPartialView. The rest code provided is to illustrate how it's already done in mvc framework.
It's also important to to seek through arrays declared in our new view engine instead of those without I18N prefix which are already there and used by default classes
Hope it will help despite answer is indirect. You can ask additional questions if you will face any difficulties.
P.S. Don't foreget to register you view engine in global.asax.cs after it will be developed.
protected virtual void Application_Start()
{
ViewEngines.Engines.Clear();
ViewEngines.Engines.Add(new I18NRazorViewEngine());
}
Related
I am using a custom Media formatter to read post data for multipartform in webapi. Handling the serialization errors and validation errors in a custom Action Filter Attribute. In the formatter I am mapping the input to a Type Object ImageMedia. I want to add any serliazation errors to the ModelState so that I can handle the those in the CustomFilterAttribute, which recieve an ActionContext. Here is the code:
public class ImageMediaFormatter : MediaTypeFormatter
{
public ImageMediaFormatter()
{
SupportedMediaTypes.Add(new MediaTypeHeaderValue("image/jpeg"));
SupportedMediaTypes.Add(new MediaTypeHeaderValue("image/jpg"));
SupportedMediaTypes.Add(new MediaTypeHeaderValue("image/png"));
SupportedMediaTypes.Add(new MediaTypeHeaderValue("image/gif"));
SupportedMediaTypes.Add(new MediaTypeHeaderValue("multipart/form-data"));
}
public override bool CanReadType(Type type)
{
return type == typeof(ImageMedia);
}
public override bool CanWriteType(Type type)
{
return false;
}
public override Task<object> ReadFromStreamAsync(
Type type, Stream stream, HttpContent request,
IFormatterLogger formatterContext)
{
return Task.Factory.StartNew<object>(() =>
{
var streamProvider = new MultipartMemoryStreamProvider();
var keys = new Dictionary<string, string>();
var result = request.ReadAsMultipartAsync(streamProvider).Result;
//get and remove random slashes from posted vaues
var categoryid =
streamProvider.Contents.First(x => x.Headers.ContentDisposition.Name.Contains("userGeneratedCategoryId")).ReadAsStringAsync().Result.Replace("\"", string.Empty);
keys.Add(Constants.UserGeneratedCategoryId, categoryid);
var imageBuffer =
streamProvider.Contents.First(x => x.Headers.ContentDisposition.Name.Contains(Constants.ImageFile)).ReadAsByteArrayAsync().Result;
return new ImageMedia(keys, imageBuffer);
});
}
}
public class ImageMedia
{
public ImageMedia(Dictionary<string, string> keys, byte[] imageBuffer)
: this()
{
var keyvaluePair = new KeyValuePair<string, string>();
foreach (var property in GetType().GetProperties())
{
try
{
keyvaluePair = keys.FirstOrDefault(pair => pair.Key.ToLower() == property.Name.ToLower());
if (!string.IsNullOrEmpty(keyvaluePair.Key))
{
property.SetValue(this, keyValuePair.Value, null);
}
}
catch (Exception ex)
{
// Add these serialization errors to the Model State so I can handle these in a Custom Validation Action Attribute
Errors.Add(keyvaluePair.Key, new List<string> { ex.Message });
IsValid = false;
}
}
Buffer = imageBuffer;
}
private ImageMedia()
{
Errors = new Dictionary<string, List<string>>();
}
public int UserGeneratedCategoryId { get; set; }
public byte[] Buffer { get;set;}
}
You could added errors to the supplied IFormatterLogger context that is passed in to ReadFromStreamAsync method:
public override Task<object> ReadFromStreamAsync(Type type, Stream stream, HttpContent request,
IFormatterLogger formatterContext)
Example:
formatterLogger.LogError(errorPath: "OrderedDate", errorMessage: "Not a valid date");
I am developing a simple validator. It works fine with server side requests but it does not work on the client side because of the forbidden post back. .Net's RequiredAttribute validator works on the client side and does not need a post back.
How can I change my validator to work like it?
My validator gets a string and checks if it is at least 5 characters long.
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field |
AttributeTargets.Parameter, AllowMultiple = false)]
public class MyValidatorAttribute : ValidationAttribute
{
private readonly int _length = 0;
public MyValidatorAttribute(int length)
{
_length = length;
}
protected override ValidationResult IsValid(object value,
ValidationContext validationContext)
{
if (value != null)
{
string data = (string)value;
if (data.Length < _length)
{
return new ValidationResult("length is short");
}
}
return ValidationResult.Success;
}
}
public class MyValidator : DataAnnotationsModelValidator<MyValidatorAttribute>
{
int minlength = 5;
string errorMsg = string.Empty;
public MyValidator(ModelMetadata metadata,
ControllerContext context,
MyValidatorAttribute attribute)
: base(metadata, context, attribute)
{
errorMsg = attribute.ErrorMessage;
}
public override IEnumerable<ModelClientValidationRule>
GetClientValidationRules()
{
ModelClientValidationRule validationRule =
new ModelClientValidationRule();
validationRule.ErrorMessage = errorMsg;
validationRule.ValidationType = "MyValidator";
validationRule.ValidationParameters.Add("minlength", minlength);
return new[] { validationRule };
}
}
I have problems with default route for admin part.
I change folder structure from default, and now I have structure how at picture
for admin
for modules
I created two ViewEngine AdminViewEngine and CoreViewEngine
AdminViewEngine
public class AdminViewEngine : RazorViewEngine
{
public AdminViewEngine()
{
AreaMasterLocationFormats = new[] { "~/Admin/Views/Shared/admin.cshtml" };
AreaPartialViewLocationFormats = new[] { "~/Admin/Views/Shared/Partials/{0}.cshtml", "~/Admin/Views/{1}/Partials/{0}.cshtml", "~/Admin/Menu/{0}.cshtml" };
AreaViewLocationFormats = new[] { "~/Admin/Views/{1}/{0}.cshtml", "~/Admin/Menu/{0}.cshtml" };
PartialViewLocationFormats = AreaPartialViewLocationFormats;
ViewLocationFormats = AreaViewLocationFormats;
MasterLocationFormats = AreaMasterLocationFormats;
}
protected override IView CreatePartialView(ControllerContext controllerContext, string partialPath)
{
return new RazorView(controllerContext, partialPath, null, false, FileExtensions);
}
protected override IView CreateView(ControllerContext controllerContext, string viewPath, string masterPath)
{
if (string.IsNullOrEmpty(masterPath))
{
masterPath = AreaMasterLocationFormats[0];
}
var view = new RazorView(controllerContext, viewPath, masterPath, true, FileExtensions);
return view;
}
}
CoreViewEngine
public class CoreViewEngine : RazorViewEngine
{
internal static readonly string Theme = SiteSettings.Instance.Theme;
public CoreViewEngine()
{
string masterCatalog = string.Format("~/Themes/{0}/Views", Theme);
string masterPath = string.Format("{0}/master.cshtml", masterCatalog);
string partialThemesFolder = string.Format("~/Themes/{0}/Partials", Theme);
MasterLocationFormats = new[] { masterPath };
ViewLocationFormats = new[] { "~/Modules/Views/{1}/{0}.cshtml" };
PartialViewLocationFormats = new[]
{
"~/Blocks/{0}.cshtml", partialThemesFolder + "/{0}.cshtml", "~/Modules/Views/{1}/Partials/{0}.cshtml",
"~/Modules/Views/{1}/{0}.cshtml"
};
}
protected override IView CreatePartialView(ControllerContext controllerContext, string partialPath)
{
return new RazorView(controllerContext, partialPath, null, false, FileExtensions, ViewPageActivator);
}
protected override IView CreateView(ControllerContext controllerContext, string viewPath, string masterPath)
{
if (string.IsNullOrEmpty(masterPath))
{
string masterCatalog = string.Format("~/Themes/{0}/Views", Theme);
masterPath = string.Format("{0}/master.cshtml", masterCatalog);
}
var view = new RazorView(controllerContext, viewPath, masterPath, true, FileExtensions, ViewPageActivator);
return view;
}
}
And I have class for registered core and admin
public class ModulSetup : BaseModule
{
public override void Setup()
{
this.SetupViewEngine();
this.SetupControllers();
}
public override void SetupRoutes(RouteCollection routes)
{
routes.MapRoute("AdminRoot", "Admin", new { controller = "Site", action = "Index" });
routes.MapRoute(
"Admin",
"Admin/{controller}/{action}/{id}",
new { controller = "Site", action = "SiteSetting", id = UrlParameter.Optional });
routes.MapRoute(
"Default",
string.Empty,
new { controller = "News", action = "LastNews" });
}
protected void SetupViewEngine()
{
ViewEngines.Engines.Add(new CoreViewEngine());
ViewEngines.Engines.Add(new AdminViewEngine());
}
protected override void SetupControllers()
{
ControllerBuilder.Current.DefaultNamespaces.Add("SGN.Core.Admin.Controllers");
}
}
Admin workin. But if I try go to default admin page _http://sitename/Admin/ I get 404
I try different variants for registered routes. But not help. I don't know what I must to do
Is it possible to use JSON.NET as default JSON serializer in ASP.NET MVC 3?
According to my research, it seems that the only way to accomplish this is to extend ActionResult as JsonResult in MVC3 is not virtual...
I hoped that with ASP.NET MVC 3 that there would be a way to specify a pluggable provider for serializing to JSON.
Thoughts?
I believe the best way to do it, is - as described in your links - to extend ActionResult or extend JsonResult directly.
As for the method JsonResult that is not virtual on the controller that's not true, just choose the right overload. This works well:
protected override JsonResult Json(object data, string contentType, Encoding contentEncoding)
EDIT 1: A JsonResult extension...
public class JsonNetResult : JsonResult
{
public override void ExecuteResult(ControllerContext context)
{
if (context == null)
throw new ArgumentNullException("context");
var response = context.HttpContext.Response;
response.ContentType = !String.IsNullOrEmpty(ContentType)
? ContentType
: "application/json";
if (ContentEncoding != null)
response.ContentEncoding = ContentEncoding;
// If you need special handling, you can call another form of SerializeObject below
var serializedObject = JsonConvert.SerializeObject(Data, Formatting.Indented);
response.Write(serializedObject);
}
EDIT 2: I removed the check for Data being null as per the suggestions below. That should make newer versions of JQuery happy and seems like the sane thing to do, as the response can then be unconditionally deserialized. Be aware though, that this is not the default behavior for JSON responses from ASP.NET MVC, which rather responds with an empty string, when there's no data.
I implemented this without the need of a base controller or injection.
I used action filters to replace the JsonResult with a JsonNetResult.
public class JsonHandlerAttribute : ActionFilterAttribute
{
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
var jsonResult = filterContext.Result as JsonResult;
if (jsonResult != null)
{
filterContext.Result = new JsonNetResult
{
ContentEncoding = jsonResult.ContentEncoding,
ContentType = jsonResult.ContentType,
Data = jsonResult.Data,
JsonRequestBehavior = jsonResult.JsonRequestBehavior
};
}
base.OnActionExecuted(filterContext);
}
}
In the Global.asax.cs Application_Start() you would need to add:
GlobalFilters.Filters.Add(new JsonHandlerAttribute());
For completion's sake, here is my JsonNetResult extention class that I picked up from somewhere else and that I modified slightly to get correct steaming support:
public class JsonNetResult : JsonResult
{
public JsonNetResult()
{
Settings = new JsonSerializerSettings
{
ReferenceLoopHandling = ReferenceLoopHandling.Error
};
}
public JsonSerializerSettings Settings { get; private set; }
public override void ExecuteResult(ControllerContext context)
{
if (context == null)
throw new ArgumentNullException("context");
if (this.JsonRequestBehavior == JsonRequestBehavior.DenyGet && string.Equals(context.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase))
throw new InvalidOperationException("JSON GET is not allowed");
HttpResponseBase response = context.HttpContext.Response;
response.ContentType = string.IsNullOrEmpty(this.ContentType) ? "application/json" : this.ContentType;
if (this.ContentEncoding != null)
response.ContentEncoding = this.ContentEncoding;
if (this.Data == null)
return;
var scriptSerializer = JsonSerializer.Create(this.Settings);
scriptSerializer.Serialize(response.Output, this.Data);
}
}
Use Newtonsoft's JSON converter:
public ActionResult DoSomething()
{
dynamic cResponse = new ExpandoObject();
cResponse.Property1 = "value1";
cResponse.Property2 = "value2";
return Content(JsonConvert.SerializeObject(cResponse), "application/json");
}
I know this is well after the question has been answered, but I'm using a different approach as I am using dependency injection to instantiate my controllers.
I have replaced the IActionInvoker ( by injecting the controller's ControllerActionInvoker Property ) with a version that overrides the InvokeActionMethod method.
This means no change to controller inheritance and it can be easily removed when I upgrade to MVC4 by altering the DI container's registration for ALL controllers
public class JsonNetActionInvoker : ControllerActionInvoker
{
protected override ActionResult InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary<string, object> parameters)
{
ActionResult invokeActionMethod = base.InvokeActionMethod(controllerContext, actionDescriptor, parameters);
if ( invokeActionMethod.GetType() == typeof(JsonResult) )
{
return new JsonNetResult(invokeActionMethod as JsonResult);
}
return invokeActionMethod;
}
private class JsonNetResult : JsonResult
{
public JsonNetResult()
{
this.ContentType = "application/json";
}
public JsonNetResult( JsonResult existing )
{
this.ContentEncoding = existing.ContentEncoding;
this.ContentType = !string.IsNullOrWhiteSpace(existing.ContentType) ? existing.ContentType : "application/json";
this.Data = existing.Data;
this.JsonRequestBehavior = existing.JsonRequestBehavior;
}
public override void ExecuteResult(ControllerContext context)
{
if (context == null)
{
throw new ArgumentNullException("context");
}
if ((this.JsonRequestBehavior == JsonRequestBehavior.DenyGet) && string.Equals(context.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase))
{
base.ExecuteResult(context); // Delegate back to allow the default exception to be thrown
}
HttpResponseBase response = context.HttpContext.Response;
response.ContentType = this.ContentType;
if (this.ContentEncoding != null)
{
response.ContentEncoding = this.ContentEncoding;
}
if (this.Data != null)
{
// Replace with your favourite serializer.
new Newtonsoft.Json.JsonSerializer().Serialize( response.Output, this.Data );
}
}
}
}
--- EDIT - Updated to show container registration for controllers. I'm using Unity here.
private void RegisterAllControllers(List<Type> exportedTypes)
{
this.rootContainer.RegisterType<IActionInvoker, JsonNetActionInvoker>();
Func<Type, bool> isIController = typeof(IController).IsAssignableFrom;
Func<Type, bool> isIHttpController = typeof(IHttpController).IsAssignableFrom;
foreach (Type controllerType in exportedTypes.Where(isIController))
{
this.rootContainer.RegisterType(
typeof(IController),
controllerType,
controllerType.Name.Replace("Controller", string.Empty),
new InjectionProperty("ActionInvoker")
);
}
foreach (Type controllerType in exportedTypes.Where(isIHttpController))
{
this.rootContainer.RegisterType(typeof(IHttpController), controllerType, controllerType.Name);
}
}
public class UnityControllerFactory : System.Web.Mvc.IControllerFactory, System.Web.Http.Dispatcher.IHttpControllerActivator
{
readonly IUnityContainer container;
public UnityControllerFactory(IUnityContainer container)
{
this.container = container;
}
IController System.Web.Mvc.IControllerFactory.CreateController(System.Web.Routing.RequestContext requestContext, string controllerName)
{
return this.container.Resolve<IController>(controllerName);
}
SessionStateBehavior System.Web.Mvc.IControllerFactory.GetControllerSessionBehavior(RequestContext requestContext, string controllerName)
{
return SessionStateBehavior.Required;
}
void System.Web.Mvc.IControllerFactory.ReleaseController(IController controller)
{
}
IHttpController IHttpControllerActivator.Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)
{
return this.container.Resolve<IHttpController>(controllerType.Name);
}
}
Expanding on the answer from https://stackoverflow.com/users/183056/sami-beyoglu, if you set the Content type, then jQuery will be able to convert the returned data into an object for you.
public ActionResult DoSomething()
{
dynamic cResponse = new ExpandoObject();
cResponse.Property1 = "value1";
cResponse.Property2 = "value2";
return Content(JsonConvert.SerializeObject(cResponse), "application/json");
}
My Post may help someone.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
namespace MultipleSubmit.Service
{
public abstract class BaseController : Controller
{
protected override JsonResult Json(object data, string contentType,
Encoding contentEncoding, JsonRequestBehavior behavior)
{
return new JsonNetResult
{
Data = data,
ContentType = contentType,
ContentEncoding = contentEncoding,
JsonRequestBehavior = behavior
};
}
}
}
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MultipleSubmit.Service
{
public class JsonNetResult : JsonResult
{
public JsonNetResult()
{
Settings = new JsonSerializerSettings
{
ReferenceLoopHandling = ReferenceLoopHandling.Error
};
}
public JsonSerializerSettings Settings { get; private set; }
public override void ExecuteResult(ControllerContext context)
{
if (context == null)
throw new ArgumentNullException("context");
if (this.JsonRequestBehavior == JsonRequestBehavior.DenyGet && string.Equals
(context.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase))
throw new InvalidOperationException("JSON GET is not allowed");
HttpResponseBase response = context.HttpContext.Response;
response.ContentType = string.IsNullOrEmpty(this.ContentType) ?
"application/json" : this.ContentType;
if (this.ContentEncoding != null)
response.ContentEncoding = this.ContentEncoding;
if (this.Data == null)
return;
var scriptSerializer = JsonSerializer.Create(this.Settings);
using (var sw = new StringWriter())
{
scriptSerializer.Serialize(sw, this.Data);
response.Write(sw.ToString());
}
}
}
}
public class MultipleSubmitController : BaseController
{
public JsonResult Index()
{
var data = obj1; // obj1 contains the Json data
return Json(data, JsonRequestBehavior.AllowGet);
}
}
I made a version that makes web service actions type-safe and simple. You use it like this:
public JsonResult<MyDataContract> MyAction()
{
return new MyDataContract();
}
The class:
public class JsonResult<T> : JsonResult
{
public JsonResult(T data)
{
Data = data;
JsonRequestBehavior = JsonRequestBehavior.AllowGet;
}
public override void ExecuteResult(ControllerContext context)
{
// Use Json.Net rather than the default JavaScriptSerializer because it's faster and better
if (context == null)
throw new ArgumentNullException("context");
var response = context.HttpContext.Response;
response.ContentType = !String.IsNullOrEmpty(ContentType)
? ContentType
: "application/json";
if (ContentEncoding != null)
response.ContentEncoding = ContentEncoding;
var serializedObject = JsonConvert.SerializeObject(Data, Formatting.Indented);
response.Write(serializedObject);
}
public static implicit operator JsonResult<T>(T d)
{
return new JsonResult<T>(d);
}
}
How do I unit test a custom ModelBinder?
Here's the code.
public class MagicBinder : DefaultModelBinder
{
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var boundModelObject = base.BindModel(controllerContext, bindingContext);
var properties = bindingContext.ModelType.GetProperties().Where(a => a.CanWrite);
foreach (var propertyInfo in properties)
{
object outValue = null;
bindingContext.TryGetValue(propertyInfo.Name, propertyInfo.DeclaringType, out outValue);
propertyInfo.SetValue(boundModelObject, outValue, null);
}
return boundModelObject;
}
}
And here is the test script.
[TestMethod]
public void TestFooBinding()
{
var dict = new ValueProviderDictionary(null)
{
{"Number", new ValueProviderResult("2", "2", null)},
{"Test", new ValueProviderResult("12", "12", null)},
};
var bindingContext = new ModelBindingContext() { ModelName = "foo", ValueProvider = dict};
var target = new MagicBinder();
Foo result = (Foo)target.BindModel(null, bindingContext);
}
public class Foo
{
public int Number { get; set; }
public int Test { get; set; }
}
Problem? In the MagicBinder, bindingContext.Model is null. If I try set it with
bindingContext.Model = new Foo(). I get an exception saying it is deprecated, and I should set the ModelMetadata.
So how do I construct a ModelMetadata? It can't even be mocked.
NOTE: This answer is for ASP.NET on .NET Framework and might be outdated.
Try like this:
[TestMethod]
public void TestFooBinding()
{
// arrange
var formCollection = new NameValueCollection
{
{ "Number", "2" },
{ "Test", "12" },
};
var valueProvider = new NameValueCollectionValueProvider(formCollection, null);
var metadata = ModelMetadataProviders.Current.GetMetadataForType(null, typeof(Foo));
var bindingContext = new ModelBindingContext
{
ModelName = "",
ValueProvider = valueProvider,
ModelMetadata = metadata
};
var controllerContext = new ControllerContext();
var sut = new MagicBinder();
// act
Foo actual = (Foo)sut.BindModel(controllerContext, bindingContext);
// assert
// TODO:
}
Incase any of you need this to work for web-api you can use this method which will test's Get Requests, you get the benefit of using the built in provider:
Which will populate the values as the would come in from the web, instead of getting bizarre side effects of creating values that the provider may potentially never return Null etc.
using System;
using System.Globalization;
using System.Net.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Metadata.Providers;
using System.Web.Http.ModelBinding;
using System.Web.Http.ValueProviders.Providers;
namespace Apps.API.Web.Tests
{
public class ModelBinderTestRule
{
//This URL is just a place holder for prefixing the query string
public const string MOCK_URL = "http://localhost:8088/";
public TModel BindModelFromGet<TBinder, TModel>(string modelName, string queryString, TBinder binder)
where TBinder : IModelBinder
{
var httpControllerContext = new HttpControllerContext();
httpControllerContext.Request = new HttpRequestMessage(HttpMethod.Get, MOCK_URL + queryString);
var bindingContext = new ModelBindingContext();
var dataProvider = new DataAnnotationsModelMetadataProvider();
var modelMetadata = dataProvider.GetMetadataForType(null, typeof(TModel));
var httpActionContext = new HttpActionContext();
httpActionContext.ControllerContext = httpControllerContext;
var provider = new QueryStringValueProvider(httpActionContext, CultureInfo.InvariantCulture);
bindingContext.ModelMetadata = modelMetadata;
bindingContext.ValueProvider = provider;
bindingContext.ModelName = modelName;
if (binder.BindModel(httpActionContext, bindingContext))
{
return (TModel)bindingContext.Model;
}
throw new Exception("Model was not bindable");
}
}
}