ارتقاء به ASP.NET Core 1.0 - قسمت 18 - کار با ASP.NET Web API
نویسنده: وحید نصیری
تاریخ: ۱۳۹۵/۰۵/۰۲ ۱۵:۲۵
آدرس: www.dntips.ir
| مطالب | ۳۶۹۴ |
| نویسندگان | ۲۷۶ |
| گروههای مطالب | ۱۰۲۴ |
| نقشههای راه | ۱۱۹ |
| دورهها | ۱۴ |
| اشتراکها | ۱۷۹۱۴ |
[Route("api/[controller]")] // http://localhost:7742/api/test
public class TestController : Controller
{
private readonly ILogger<TestController> _logger;
public TestController(ILogger<TestController> logger)
{
_logger = logger;
} [Route("api/[controller]")] // http://localhost:7742/api/test
public class TestController : Controller
{
private readonly ILogger<TestController> _logger;
public TestController(ILogger<TestController> logger)
{
_logger = logger;
}
[HttpGet]
public IEnumerable<string> Get() // http://localhost:7742/api/test
{
return new [] { "value1", "value2" };
}
[HttpGet("{page:int}")]
public IActionResult Get(int page) // http://localhost:7742/api/test/1
{
return Json(new[] { "value3", "value4" });
}
[HttpGet("/api/path1")]
public IActionResult GetEpisodes1() // http://localhost:7742/api/path1
{
return Json(new[] { "value5", "value6" });
}
[HttpGet("/api/path2")]
public IActionResult GetEpisodes2() // http://localhost:7742/api/path2
{
try
{
// get data from the DB ...
return Ok(new[] { "value7", "value8" });
}
catch (Exception ex)
{
_logger.LogError("Failed to get data from the API", ex);
return BadRequest();
}
}
} [Route("api/[controller]")]
public class ValuesController : Controller
{
// GET: api/values
[HttpGet]
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
// GET api/values/5
[HttpGet("{id}")]
public string Get(int id)
{
return "value";
}
// POST api/values
[HttpPost]
public void Post([FromBody]string value)
{
}
// PUT api/values/5
[HttpPut("{id}")]
public void Put(int id, [FromBody]string value)
{
}
// DELETE api/values/5
[HttpDelete("{id}")]
public void Delete(int id)
{
}
}
} [Produces("application/json")]
[Route("api/[controller]")] // http://localhost:7742/api/test
public class TestController : Controller namespace Core1RtmEmptyTest.Models
{
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
}
} using Core1RtmEmptyTest.Models;
using Microsoft.AspNetCore.Mvc;
namespace Core1RtmEmptyTest.Controllers
{
public class PersonController : Controller
{
public IActionResult Index()
{
return View();
}
[HttpPost]
public IActionResult Index(Person person)
{
return Json(person);
}
}
} @section scripts
{
<script type="text/javascript">
$(function () {
$.ajax({
type: 'POST',
url: '/Person/Index',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({
FirstName: 'F1',
LastName: 'L1',
Age: 23
}),
success: function (result) {
console.log('Data received: ');
console.log(result);
}
});
});
</script>
}
public IActionResult Index([FromBody]Person person)
var dataType = 'application/x-www-form-urlencoded; charset=utf-8';
var data = $('form').serialize(); [HttpPost] public IActionResult Index([FromForm]Person person)
public class ProductModel
{
public ProductModel(IProductService prodService)
{
Value = prodService.Get(productId);
}
public IProduct Value { get; private set; }
} public async Task<IActionResult> GetProduct([FromServices]ProductModel product)
{
} public void ConfigureServices(IServiceCollection services)
{
services.AddMvc(options =>
{
options.FormatterMappings.SetMediaTypeMappingForFormat("xml", new MediaTypeHeaderValue("application/xml"));
}).AddJsonOptions(options =>
{
options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
options.SerializerSettings.DefaultValueHandling = DefaultValueHandling.Include;
options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
}); services.AddMvc().AddJsonOptions(opt =>
{
var resolver = opt.SerializerSettings.ContractResolver;
if (resolver != null)
{
var res = resolver as DefaultContractResolver;
res.NamingStrategy = null; // this is what removes the camelcasing
}
}); public class ProductModel
{
public ProductModel(IContextAccessor<ActionContext> action, IProductService prodService)
{
//TODO: Do some error checking...
var productId = action.Value.RouteData.Values["product"];
Value = prodService.Get(productId);
}
public IProduct Value { get; private set; }
} public Task<IActionResult> RefreshToken(string refreshToken)
{
"refreshToken": "test"
} public Task<IActionResult> RefreshToken([FromBody]JToken jsonBody)
{
var refreshToken = jsonBody.Value<string>("refreshToken"); public class EntityData
{
public string RefreshToken { get; set; }
} Microsoft.AspNetCore.Mvc.Core Microsoft.AspNetCore.Mvc.Cors Microsoft.AspNetCore.Mvc.Formatters.Json
namespace AspNetCoreWebAPIOnly
{
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
var mvcCoreBuilder = services.AddMvcCore();
mvcCoreBuilder
.AddFormatterMappings()
.AddJsonFormatters()
.AddCors();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseMvc();
}
}
} namespace AspNetCoreWebAPIOnly.Controllers
{
[Route("api/[controller]")]
// ControllerBase instead of Controller
public class ValuesController : ControllerBase
{
// GET api/values
[HttpGet]
public IEnumerable<string> Get()
{
return new[] { "value1", "value2" };
}
}
} [ApiController]
[Route("api/users")]
public class UserController : ControllerBase
{
[HttpGet("{id:int}")]
public ActionResult GetUserById(int id)
{
var user = new { Id = 1, Name = "Sirwan Afifi" };
return Ok(user);
}
[HttpPost]
public ActionResult CreateUser(CreateUserDto user)
{
return CreatedAtAction(nameof(GetUserById), new { user.Id }, user);
}
}
اطلاعات بیشتر (+)
[Route("api/[controller]")]
[ApiController]
public class ProductsController : ControllerBase
{ services.AddMvc()
.SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
.ConfigureApiBehaviorOptions(options =>
{
options.InvalidModelStateResponseFactory = context =>
{
var problemDetails = new ValidationProblemDetails(context.ModelState)
{
Type = "https://contoso.com/probs/modelvalidation",
Title = "One or more model validation errors occurred.",
Status = StatusCodes.Status400BadRequest,
Detail = "See the errors property for details.",
Instance = context.HttpContext.Request.Path
};
return new BadRequestObjectResult(problemDetails)
{
ContentTypes = { "application/problem+json" }
};
};
}); public class UserModel
{
[Required, EmailAddress]
public string Email { get; set; }
[Required, StringLength(1000)]
public string Name { get; set; }
} public IActionResult SaveUser(UserModel model)
{
if(!ModelState.IsValid)
{ public IActionResult SaveUser(
[Required, EmailAddress] string Email
[Required, StringLength(1000)] string Name)
{
if(!ModelState.IsValid) public IActionResult Get([BindRequired, FromRoute] Guid testId, [BindRequired, FromQuery] int qty)
{
if(!ModelState.IsValid) [HttpPost("[action]")]
public bool Test([Required]string name)
{
return true;
} public void ConfigureServices(IServiceCollection services)
{
services.AddMvc()
.AddNewtonsoftJson();
} public void ConfigureServices(IServiceCollection services)
{
services.AddMvc()
.AddNewtonsoftJson();
} [Route("api/[controller]")]
[Authorize]
[ApiController]
public class UserApiController : Controller
{
private readonly IUserService _userService;
public UserApiController(IUserService userService)
{
_userService = userService;
}
[HttpPost("[action]")]
public async Task<IActionResult> GetCustomers([FromBody] CustomersFilterViewModel filter)
{
var model = await _userService.GetCustomers(filter);
return Ok(model);
}
}
const options = {headers: {'Content-Type': 'application/json'}};
axios.post(url, JSON.stringify({ data}), options) //ViewModels
public class CustomListItem
{
public int Id { get; set; }
public string Text { get; set; }
}
public class ProductAddGetViewModel
{
public IEnumerable<CustomListItem> Categories { get; set; }
public IEnumerable<CustomListItem> Groups { get; set; }
}
public class ProductAddViewModel
{
public string Name { get; set; }
public bool IsActive { get; set; }
public int CategoryId { get; set; }
public int GroupId { get; set; }
}
public class ProductEditGetViewModel
{
public int Id { get; set; }
public string Name { get; set; }
public IEnumerable<CustomListItem> Categories { get; set; }
public IEnumerable<CustomListItem> Groups { get; set; }
}
public class ProductEditViewModel
{
public int Id { get; set; }
public string Name { get; set; }
public int CategoryId { get; set; }
public int GroupId { get; set; }
} // ProductsController - ApiControler
// GET: api/products/views/add
[HttpGet("views/add")]
public async Task<IActionResult> GetAdd()
{
ProductAddGetViewModel model = await _productService.GetAddModelAsync();
return Ok(model)
}
// POST: api/products
[HttpPost]
public async Task<IActionResult> Add(ProductAddViewModel model)
{
...
}
// GET: api/products/5/views/edit
[HttpGet("{id}/views/edit")]
public async Task<IActionResult> GetEdit(int id)
{
ProductEditGetViewModel model = await _productService.GetEditModelAsync(id);
return Ok(model)
}
// PUT: api/products/5
[HttpPut("{id}")]
public async Task<IActionResult> Edit(int id, ProductEditViewModel model)
{
...
} The JSON value could not be converted to System.Int32
{
"$.time": [
"The JSON value could not be converted to System.DateTime. Path: $.time | LineNumber: 1 | BytePositionInLine: 23."
]
} 2019-06-14T02:30:04.0576719Z
'Full date'
"yyyy'-'MM'-'dd"
"'Full date''T''Hour'':''Minute'"
"yyyy'-'MM'-'dd'T'HH':'mm"
"'Full date''T''Partial time'"
"yyyy'-'MM'-'dd'T'HH':'mm':'ss" (The Sortable ("s") Format Specifier)
"yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'FFFFFFF"
"'Full date''T''Time hour'':''Minute''Time offset'"
"yyyy'-'MM'-'dd'T'HH':'mmZ"
"yyyy'-'MM'-'dd'T'HH':'mm('+'/'-')HH':'mm"
'Date time'
"yyyy'-'MM'-'dd'T'HH':'mm':'ssZ"
"yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'FFFFFFFZ"
"yyyy'-'MM'-'dd'T'HH':'mm':'ss('+'/'-')HH':'mm"
"yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'FFFFFFF('+'/'-')HH':'mm" https://localhost:44393/time?time=2019-06-14T02:30:04.0576719Z
Model-bound value is: 2019-06-13T19:30:04.0576719-07:00, Kind is: Local
[BindProperty, DisplayFormat(DataFormatString = "{0:yyyy-MM-ddTHH:mm}", ApplyFormatInEditMode = true)]
public DateTime DateTime { get; set; }
DateTime: <input asp-for="DateTime" asp-format="{0:yyyy-MM-ddTHH:mm}" /> Services.AddScoped<SomeCustomType>();
[Route("[controller]")]
[ApiController]
public class MyController : ControllerBase
{
// Binding from the services
[HttpPost]
public ActionResult Post(SomeCustomType service) => Ok();
} services.Configure<ApiBehaviorOptions>(options =>
{
options.DisableImplicitFromServicesParameters = true;
}); using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Options;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddSingleton<BigCacheConsumer>();
builder.Services.AddSingleton<SmallCacheConsumer>();
builder.Services.AddKeyedSingleton<IMemoryCache, BigCache>("big");
builder.Services.AddKeyedSingleton<IMemoryCache, SmallCache>("small");
var app = builder.Build();
app.MapGet("/big", (BigCacheConsumer data) => data.GetData());
app.MapGet("/small", (SmallCacheConsumer data) => data.GetData());
app.Run();
class BigCacheConsumer([FromKeyedServices("big")] IMemoryCache cache)
{
public object? GetData() => cache.Get("data");
}
class SmallCacheConsumer(IKeyedServiceProvider keyedServiceProvider)
{
public object? GetData() => keyedServiceProvider.GetRequiredKeyedService<IMemoryCache>("small");
} var builder = WebApplication.CreateBuilder(args);
builder.Services.Configure<MvcOptions>(options =>
{
options.AllowEmptyInputInBodyModelBinding = true;
}); public IActionResult Post([FromBody(EmptyBodyBehavior = EmptyBodyBehavior.Allow)] MyBody? body)
{
// body will be null if the request Content-Length == 0
} public class ExampleController : Controller
{
public IActionResult Post(MyBody? body) // Nullable
{
// body will be null if the request Content-Length == 0
}
public IActionResult Post(MyBody body) // Non-nullable
{
// Request will fail with a 400 and "A non-empty request body is required."
// when Content-Length == 0
}
}