在.NET核心请求,C#中的表单字段中替换一些字符?

我想在我的web api .Net核心请求中替换所有۱字符与1
如:
Number ۱应该转换为Number 1
在MVC 5我以前HttpModule,在.NET的核心我用中间件如下:在.NET核心请求,C#中的表单字段中替换一些字符?

namespace VistaBest.Api 

{

public class PersianCharsMiddleware

{

private readonly RequestDelegate _next;

public PersianCharsMiddleware(RequestDelegate next)

{

_next = next;

}

public Task Invoke(HttpContext httpContext)

{

var collection = httpContext.Request.Form;

foreach (var controlKey in collection.Keys.Where(controlKey => !controlKey.StartsWith("__")))

{

collection[controlKey] = collection[controlKey].ToString().Replace("۱", "1");

}

return _next(httpContext);

}

}

public static class PersianCharsMiddlewareExtensions

{

public static IApplicationBuilder UsePersianCharsMiddleware(this IApplicationBuilder builder)

{

return builder.UseMiddleware<PersianCharsMiddleware>();

}

}

}

collection[controlKey]是只读的,我不能赋值给它?
实际上,我必须编辑窗体的所有字符串字段,我应该怎么做?
我可以使用自定义模型绑定器吗?

回答:

我可以将其与自定义模型粘合剂写:

public class PersianCharsModelBinder : IModelBinder 

{

private readonly IModelBinder _simpleTypeModelBinder;

public PersianCharsModelBinder(IModelBinder simpleTypeModelBinder)

{

_simpleTypeModelBinder = simpleTypeModelBinder;

}

public Task BindModelAsync(ModelBindingContext bindingContext)

{

var valueProviderResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);

if (valueProviderResult == ValueProviderResult.None) return _simpleTypeModelBinder.BindModelAsync(bindingContext);

bindingContext.ModelState.SetModelValue(bindingContext.ModelName, valueProviderResult);

var valueAsString = valueProviderResult.FirstValue;

if (string.IsNullOrWhiteSpace(valueAsString)) return _simpleTypeModelBinder.BindModelAsync(bindingContext);

var model = valueAsString.ToEnglishNumber().RemoveArabicChars();

bindingContext.Result = ModelBindingResult.Success(model);

return Task.CompletedTask;

}

}

public class PersianCharsBinderProvider : IModelBinderProvider

{

public IModelBinder GetBinder(ModelBinderProviderContext context)

{

if (context == null) throw new ArgumentNullException(nameof(context));

if (context.Metadata.IsComplexType) return null;

var simpleTypeModelBinder = new SimpleTypeModelBinder(context.Metadata.ModelType);

if (context.Metadata.ModelType == typeof(string)) return new PersianCharsModelBinder(simpleTypeModelBinder);

return simpleTypeModelBinder;

}

}

Startup.cs

services.AddMvc(options => 

{

options.ModelBinderProviders.Insert(0, new PersianCharsBinderProvider());

});

以上是 在.NET核心请求,C#中的表单字段中替换一些字符? 的全部内容, 来源链接: utcz.com/qa/264980.html

回到顶部