What URI should I enter to run my Web API2? - c#

What URI should I enter to run my Web API 2 rating route?
I have tried the following URIs with POST method and I get 404 errors:
http://localhost:52229/PersonalAutoAPI/RunRating
This one works (different controller):
http://localhost:52229/PersonalAutoAPI/Drivers
I can GET my driver API
Here is my webapiconfig.config.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
namespace PersonalAuto
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "PersonalAutoAPI",
routeTemplate: "PersonalAutoAPI/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
var appXmlType = config.Formatters.XmlFormatter.SupportedMediaTypes.FirstOrDefault(t => t.MediaType == "application/xml");
config.Formatters.XmlFormatter.SupportedMediaTypes.Remove(appXmlType);
}
}
}
Here it is my RatingControler.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using PersonalAuto.Models;
namespace PersonalAuto.Controllers
{
public class RatingControler : ApiController
{
public IEnumerable<RatingResult> PostRunRaing([FromBody] RatingInfo MyRateInfo)
{
RatingResult[] myRatingResult =
{new RatingResult{PremiumDP = 0M,PremiumEFTDownPament = 0M,PremiumMontlyPayment = 0M,PremiumEFTMonthlyPayment=0M,PremiumPIF=0M }
};
return myRatingResult;
}
public IHttpActionResult PostRunRating([FromBody] RatingInfo MyRateInfo)
{
RatingResult MyRating = new RatingResult { PremiumDP = 0M, PremiumEFTDownPament = 0M, PremiumMontlyPayment = 0M, PremiumEFTMonthlyPayment = 0M, PremiumPIF = 0M };
if (MyRating == null)
{
return NotFound();
}
return Ok(MyRating);
}
}
}
Here it is my diverscontroler.cs (this works with above uri)
using PersonalAuto.Models;
using System;
using System.Collections.Generic;
using System.Text;
using System.Web.Http;
using System.Linq;
using System.Net.Http;
using System.IO;
namespace PersonalAuto.Controllers
{
public class DriversController : ApiController
{
public IEnumerable<Driver> GetAllDrivers()
{
Driver[] myDriverArray =
{
new Driver { id = "1234", first_name = "eric", last_name = "last", dl_number = "1234", address_1 = "1234 test st", address_2 = "", city = "dallas", state = "TX", zip = "75248", mobile = "214-415-9224" }
};
return myDriverArray;
}
public IHttpActionResult GetDriverByLicenseNo(string drivers_license_number, string drivers_license_state)
{
string PreToken = "xxxxx:xxx:xxxxxxxxxxxxx";
string Token = Convert.ToBase64String(Encoding.UTF8.GetBytes(PreToken));
if (drivers_license_state == null)
drivers_license_state = "TX";
var driver = new Driver { id = Token, first_name = "eric", last_name = "last", dl_number = "1234", address_1 = "1234 test st", address_2 = "", city = "dallas", state = "TX", zip = "75248", mobile = "214-415-9224" }; // products.FirstOrDefault((p) => p.Id == id);
if (driver == null)
{
return NotFound();
}
return Ok(driver);
}
}
}
I have been pulling my hair out over this! Any help would be appreciated!

The routing setup depends on the controller class name ending in Controller. In your sample code, you have it misspelled: RatingControler should be RatingController
Also check the spelling of PostRunRaing - which seems like it should be PostRunRating, (but it can't be because then you would have a naming conflict. The controller wouldn't know whether to return an IEnumerable or an IHttpActionResult.)
Fix that, and then I think your route will be:
http://localhost:52229/PersonalAutoAPI/Rating/PostRunRating

There code has two problem:
Change RatingControler to RatingController. The controller factory doesn't recognize RatingControler because it expects *Controller.
you cannot have two method with same http verb and method name. you can not overload methods in controllers.

Related

C# System.InvalidOperationException DisplayClass0_0 error while getting token

I need to get token when I register, but it gives me an error
Hello everyone.
I got that error when I was trying to register to my project on Postman:
https://anotepad.com/note/read/tgrka47d
(System.InvalidOperationException: An exception was thrown while attempting to evaluate the LINQ query parameter expression 'value(DataAccess.Concrete.EntityFramework.EfUserDal+<>c__DisplayClass0_0).user.Id'. See the inner exception for more information.)
My UserManager is here:
`
using System.Collections.Generic;
using Business.Abstract;
using Core.Entities.Concrete;
using DataAccess.Abstract;
namespace Business.Concrete
{
public class UserManager : IUserService
{
IUserDal _userDal;
public UserManager(IUserDal userDal)
{
_userDal = userDal;
}
public List<OperationClaim> GetClaims(User user)
{
return _userDal.GetClaims(user);
}
public void Add(User user)
{
_userDal.Add(user);
}
public User GetByMail(string email)
{
return _userDal.Get(u => u.Email == email);
}
}
}
`
My AuthManager is here:
`
using Business.Abstract;
using Business.Constants;
using Core.Entities.Concrete;
using Core.Utilities.Results;
using Core.Utilities.Security.Hashing;
using Core.Utilities.Security.JWT;
using Entities.DTOs;
namespace Business.Concrete
{
public class AuthManager : IAuthService
{
private IUserService _userService;
private ITokenHelper _tokenHelper;
public AuthManager(IUserService userService, ITokenHelper tokenHelper)
{
_userService = userService;
_tokenHelper = tokenHelper;
}
public IDataResult<User> Register(UserForRegisterDto userForRegisterDto, string password)
{
byte[] passwordHash, passwordSalt;
HashingHelper.CreatePasswordHash(password, out passwordHash, out passwordSalt);
var user = new User
{
Email = userForRegisterDto.Email,
FirstName = userForRegisterDto.FirstName,
LastName = userForRegisterDto.LastName,
PasswordHash = passwordHash,
PasswordSalt = passwordSalt,
Status = true
};
_userService.Add(user);
return new SuccessDataResult<User>(user, Messages.UserRegistered);
}
public IDataResult<User> Login(UserForLoginDto userForLoginDto)
{
var userToCheck = _userService.GetByMail(userForLoginDto.Email);
if (userToCheck == null)
{
return new ErrorDataResult<User>(Messages.UserNotFound);
}
if (!HashingHelper.VerifyPasswordHash(userForLoginDto.Password, userToCheck.PasswordHash, userToCheck.PasswordSalt))
{
return new ErrorDataResult<User>(Messages.PasswordError);
}
return new SuccessDataResult<User>(userToCheck, Messages.SuccessfulLogin);
}
public IResult UserExists(string email)
{
if (_userService.GetByMail(email) != null)
{
return new ErrorResult(Messages.UserAlreadyExists);
}
return new SuccessResult();
}
public IDataResult<AccessToken> CreateAccessToken(User user)
{
var claims = _userService.GetClaims(user);
var accessToken = _tokenHelper.CreateToken(user, claims);
return new SuccessDataResult<AccessToken>(accessToken, Messages.AccessTokenCreated);
}
}
}
`
My AuthController is here:
`
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Business.Abstract;
using Entities.DTOs;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace WebAPI.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class AuthController : Controller
{
private IAuthService _authService;
public AuthController(IAuthService authService)
{
_authService = authService;
}
[HttpPost("login")]
public ActionResult Login(UserForLoginDto userForLoginDto)
{
var userToLogin = _authService.Login(userForLoginDto);
if (!userToLogin.Success)
{
return BadRequest(userToLogin.Message);
}
var result = _authService.CreateAccessToken(userToLogin.Data);
if (result.Success)
{
return Ok(result.Data);
}
return BadRequest(result.Message);
}
[HttpPost("register")]
public ActionResult Register(UserForRegisterDto userForRegisterDto)
{
var userExists = _authService.UserExists(userForRegisterDto.Email);
if (!userExists.Success)
{
return BadRequest(userExists.Message);
}
var registerResult = _authService.Register(userForRegisterDto,userForRegisterDto.Password);
var result = _authService.CreateAccessToken(registerResult.Data);
if (result.Success)
{
return Ok(result.Data);
}
return BadRequest(result.Message);
}
}
}
`
My EfUserDal is here:
`
using System.Collections.Generic;
using Core.DataAccess.EntityFramework;
using Core.Entities.Concrete;
using DataAccess.Abstract;
using System.Linq;
namespace DataAccess.Concrete.EntityFramework
{
public class EfUserDal : EfEntityRepositoryBase<User,CarRentalContext>,IUserDal
{
public List<OperationClaim> GetClaims(User user)
{
using (CarRentalContext context = new CarRentalContext())
{
var result = from operationClaim in context.OperationClaims
join userOperationClaim in context.UserOperationClaims
on operationClaim.Id equals userOperationClaim.OperationClaimId
where userOperationClaim.UserId == user.Id
select new OperationClaim {Id = operationClaim.Id, Name = operationClaim.Name};
return result.ToList();
}
}
}
}
`
I need to get a token when I register. How can I fix this?
You picked up the wrong lines from your stacktrace to focus on.
It states the following in the inner exception:
System.NullReferenceException: Object reference not set to an instance of an object.
at DataAccess.Concrete.EntityFramework.EfUserDal.GetClaims(User user) in /home/mert/Desktop/Project/ReCapProject/DataAccess/Concrete/EntityFramework/EfUserDal.cs:line 20
Which means you have a variable on line 20 in your EfUserDal which does not have a value at runtime.
Since the next line mentions ToList, I'm guessing result is null after evaluating the query. Use debugging to see what value each variable in your query is getting before it's evaluated. Probably one of them is null

Add a filter for a header in Swagger for ASP .NET Core 3.1

I have followed this:
Web Api How to add a Header parameter for all API in Swagger
and this:
How to send custom headers with requests in Swagger UI?
However, none of these IParameter, Parameter or NonBodyParameters work on ASP .NET CORE 3.1.
I would like to add a header on my swagger which takes a tenant-ID that is preferably taken from the logged user.
I have also went through this as well:
https://github.com/domaindrivendev/Swashbuckle.AspNetCore
Can anyone point me to the right direction?
using Swashbuckle.AspNetCore.Swagger;
using Swashbuckle.AspNetCore.SwaggerGen;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc.ApiExplorer;
using Microsoft.AspNetCore.JsonPatch.Operations;
using Microsoft.OpenApi.Models;
namespace Intent2.Auth.Utils
{
public class AddRequiredHeaderParameter : IOperationFilter
{
public void Apply(OpenApiOperation operation, OperationFilterContext context)
{
if (operation.Parameters == null)
operation.Parameters = new List<IParameter>();
operation.Parameters.Add(new NonBodyParameter
{
Name = "X-User-Token",
In = "header",
Type = "string",
Required = false
});
}
}
}
services.AddSwaggerGen(options =>
{
options.OperationFilter<AddRequiredHeaderParameter>();
}
With the latest version of Swashbuckle compatible with ASP.NET Core 3.1 many types have been replaced by equivalent types in the Microsoft.OpenApi.Models namespace. So you shouldn't use anymore types like NonBodyParameter or IParameter. Both of these have been replaced by a single class OpenApiParameter.
Your code should look like this
using Microsoft.OpenApi.Any;
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen;
using System.Collections.Generic;
namespace Intent2.Auth.Utils
{
public class AddRequiredHeaderParameter : IOperationFilter
{
public void Apply(OpenApiOperation operation, OperationFilterContext context)
{
if (operation.Parameters == null)
operation.Parameters = new List<OpenApiParameter>();
operation.Parameters.Add(new OpenApiParameter()
{
Name = "X-User-Token",
Description = "Access Token",
In = ParameterLocation.Header,
Schema = new OpenApiSchema() { Type = "String" },
Required = true,
Example = new OpenApiString("Tenant ID example")
});
}
}
}
Then in your startup, simply inject SwaggerGen as usual
services.AddSwaggerGen(options =>
{
options.OperationFilter<AddRequiredHeaderParameter>();
}
You can even make the Tenant ID coming from the outside like a configuration file for example. To do that, modify your AddRequiredHeaderParameter as follow
using Microsoft.OpenApi.Any;
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen;
using System;
using System.Collections.Generic;
namespace Intent2.Auth.Utils
{
public class AddRequiredHeaderParameter : IOperationFilter
{
private string _tenantIdExample;
public AddRequiredHeaderParameter(string tenantIdExample)
{
if (string.IsNullOrEmpty(tenantIdExample ))
throw new ArgumentNullException(nameof(tenantIdExample ));
_tenantIdExample = tenantIdExample;
}
public void Apply(OpenApiOperation operation, OperationFilterContext context)
{
if (operation.Parameters == null)
operation.Parameters = new List<OpenApiParameter>();
operation.Parameters.Add(new OpenApiParameter()
{
Name = "X-User-Token",
Description = "Access Token",
In = ParameterLocation.Header,
Schema = new OpenApiSchema() { Type = "String" },
Required = true,
Example = new OpenApiString(_tenantIdExample)
});
}
}
}
And call it that way from your startup
services.AddSwaggerGen(options =>
{
options.OperationFilter<AddRequiredHeaderParameter>("Tenant ID example");
}
By the way I think if your class is called AddRequiredHeaderParameter you should actually set Required = true instead of false

CORS issue in .Net Framework 4.5 with Angular 6

I have created API in .Net Framework 4.5 and it's working fine in Postman but When I am implementing with Angular7 then we didn't get Requested Parameters like (Username and Password) in API.
I have already tried these steps:
I have already installed this package
Microsoft.AspNet.WebApi.Cors
DemoController.cs
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
using System.Web.Http.Cors;
using System.Web.Http.Description;
using TestData.Models;
namespace TestData.Controllers
{
public class DemoController : ApiController
{
[HttpPost]
[Route("api/Demo/Login")]
public IHttpActionResult Login(HttpRequestMessage request)
{
string username = HttpContext.Current.Request.Form["Username"]; // getting Null
string pass = HttpContext.Current.Request.Form["Pass"]; // getting Null
return Ok('Username: ' +username + 'Password :' +pass);
}
}
}
WebApiConfig.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
using System.Web.Http.Cors;
namespace TestData
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
EnableCorsAttribute cors = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(cors);
}
}
}
I am using some code of Angular
auth.service.ts
import { Injectable } from '#angular/core';
import { HttpClient, HttpHeaders } from '#angular/common/http';
#Injectable({
providedIn: 'root'
})
export class AuthService {
apiUrl : any = 'http://mydomain/api';
constructor(private http : HttpClient) { }
GetHttpHeaders() : HttpHeaders {
const headers = new HttpHeaders().set('Content-Type', 'application/json');
return headers;
}
loginUser() {
var data = JSON.stringify({
"Username" : '3333',
"Pass" : '123456'
})
return this.http.post(this.apiUrl+'/Demo/Login', data, { headers : this.GetHttpHeaders() }).subscribe((results) => {
console.log(results);
});
}
}
In UI you have added 'Content-Type', 'application/json', So it is better if you accept parameter of type object in ActionResult.
Try this Solution:
Backend:
public IHttpActionResult Login(JObject request)
{
string username = Convert.ToString(request.SelectToken("Username"))
...
}
UI:
loginUser(){
var data = {
"Username" : '3333',
"Password" : '123456'
}
return this.http.post(this.apiUrl+'/Demo/Login', data, { headers : this.GetHttpHeaders() }).subscribe((results) => {
console.log(results);
});
}
Another way is to create a Model Class:
public class LoginRequestDTO
{
public string Username{ get; set; }
public string Password{ get; set; }
}
and ActionResult:
public IHttpActionResult Login(LoginRequestDTO request)
{
string username = request.Username;
...
}

c# - 405 (Method Not Allowed) when POST from Angular 2 app

I'm a bit desperate with this issue. I'm new on angular 2 and .net and I trying to build a simple application. I programmed an api rest in c#. When i call a GET method from angular it works fine, but not POSTmethod. I receive 405 (Method not allowed) all the time, but if i call the post with postman all works. I see lots of issues with the same problem, but they doesn't work for me.
I have CORS enabled.
Here's my code:
Angular
sendPtipo(delegacion,municipio,ejercicio,recinto,tipo){
let headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded' });
let options = new RequestOptions({ headers: headers });
let urlPtipo ='http://localhost:50790/ApiProductoTipo/CalculaPTRecinto';
let body ='delegacion='+delegacion+'&municipio='+municipio+'&recinto='+recinto+'&ejercicio='+ejercicio+'&tipo'+tipo;
return this._http.post(urlPtipo , body , options)
.map(data => {alert('ok');})
.catch(this.handleError);
}
private extractData(res: Response) {
let body = res.json();
return body.data || {};
}
private handleError(error: Response) {
console.error(error);
return Observable.throw(error.json().error || 'Server error');
}}
Api rest in C#
using System.Collections.Generic;
using System.Web.Http;
using AppName.Models;
using AppName.Service;
using System.Linq;
using AppName.ViewModels;
using System.Net.Http;
using System.Net;
using System.Web.Http.Cors;
namespace Api.Services
{
// Allow CORS for all origins. (Caution!)
//[EnableCors(origins: "*", headers: "*", methods: "*")]
public class ApiProductoTipoController : ApiController
{
private readonly IProductoTipoService productoTipoService;
public HttpResponseMessage Options()
{
return new HttpResponseMessage { StatusCode = HttpStatusCode.OK };
}
public ApiProductoTipoController(IProductoTipoService productoTipoService)
{
this.productoTipoService = productoTipoService;
}
[HttpPost]
[Route("~/ApiProductoTipo/CalculaPTRecinto")]
public HttpResponseMessage CalculaPTRecinto([FromBody]int delegacion, int municipio, int ninterno, int ejercicio, string tipo)
{
if (this.productoTipoService.CalculaPTRecinto(delegacion, municipio, ninterno, ejercicio, tipo) != 0)
{
return Request.CreateResponse(HttpStatusCode.OK);
}
else
{
return Request.CreateResponse(HttpStatusCode.BadRequest);
}
}
}}
webapiconfig.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
using System.Web.Http.Cors;
namespace Web
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
//Enable cors
var cors = new EnableCorsAttribute("*", "accept,accesstoken,authorization,cache-control,pragma,content-type,origin", "GET,PUT,POST,DELETE,TRACE,HEAD,OPTIONS");
//var cors = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(cors);
//Configuramos el MapRoute
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
config.Routes.MapHttpRoute(
name: "ApiWithAction",
routeTemplate: "{controller}/{action}/{id}",
defaults: new { action = RouteParameter.Optional, id = RouteParameter.Optional }
);
}
}
}
Log
headers:Headers
ok:false
status:405
statusText:"Method Not Allowed"
type:2
url:"http://localhost:50790/ApiProductoTipo/CalculaPTRecinto"
_body:"{"Message":"The requested resource does not support http method 'POST'."}"
Any idea? Thank you for reading!
Edit: this was the response of Postman 200 OK
Cache-Control →no-cache
Content-Length →0
Date →Fri, 26 May 2017 09:48:05 GMT
Expires →-1
Pragma →no-cache
Server →Microsoft-IIS/10.0
X-AspNet-Version →4.0.30319
X-Powered-By →ASP.NET
X-SourceFiles →=?UTF-8?B?QzpcVXNlcnNcNzAyNTU3MjFKXERlc2t0b3BcQXBpUHJvZHVjdG9UaXBvXFdlYlxBcGlQcm9kdWN0b1RpcG9cQ2FsY3VsYVBUUmVjaW50bw==?=
Your code seems ok.Try to change code as I have given below :
Angular
sendPtipo(delegacion: number,municipio: number,ejercicio: number,recinto: number,tipo: string){
let data = new Object();
data.delegacion = delegacion;
data.municipio = municipio;
data.ejercicio = ejercicio;
data.recinto = recinto;
data.tipo = tipo;
let headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded' });
let options = new RequestOptions({ headers: headers });
let urlPtipo ='http://localhost:50790/ApiProductoTipo/CalculaPTRecinto';
return this._http.post(urlPtipo , data , options)
.map(data => {alert('ok');})
.catch(this.handleError);
}
private extractData(res: Response) {
let body = res.json();
return body.data || {};
}
private handleError(error: Response) {
console.error(error);
return Observable.throw(error.json().error || 'Server error');
}}
API in C#
using System.Collections.Generic;
using System.Web.Http;
using AppName.Models;
using AppName.Service;
using System.Linq;
using AppName.ViewModels;
using System.Net.Http;
using System.Net;
using System.Web.Http.Cors;
namespace Api.Services
{
// Allow CORS for all origins. (Caution!)
//[EnableCors(origins: "*", headers: "*", methods: "*")]
public class ApiProductoTipoController : ApiController
{
public class myobj{
public int delegacion { get; set; }
public int municipio { get; set; }
public int ejercicio { get; set; }
public int recinto { get; set; }
public string tipo { get; set; }
}
private readonly IProductoTipoService productoTipoService;
public HttpResponseMessage Options()
{
return new HttpResponseMessage { StatusCode = HttpStatusCode.OK };
}
public ApiProductoTipoController(IProductoTipoService productoTipoService)
{
this.productoTipoService = productoTipoService;
}
[HttpPost]
[Route("~/ApiProductoTipo/CalculaPTRecinto")]
public HttpResponseMessage CalculaPTRecinto(myobj data)
{
var tipo = data.tipo;
...
}
}}
I was facing the same issue.The actual datatype of data you sre sending can't get at API side.That's why its giving 405 error.So try to send data as an object and also receive as an object at API side.
Hope this will help you

Retrofit + Restful c# Upload Files

I got the files to send by Retrofit with Android using Multiparti however on my server I work with .Net C# to build the Restful Service, then How can i create the restful to receive the files multiparti from Retrofit / Android?
sample:
[RoutePrefix("rest/files")]
public class ReceiveImagesController : ApiController
{
[AcceptVerbs("POST")]
[Route("SendFiles")]
public string sendFiles()
{
string retorno = "";
string path = "C:/temp";
// byte[] Bytes = new byte[files.Inpu]
return retorno;
}
}
My sample code and I use file upload in webapi 2. I think your problem will solve below codes.
sing System;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;
namespace WebMvcTest.Controllers
{
[System.Web.Http.RoutePrefix("api/test")]
public class FileUploadController : ApiController
{
[System.Web.Http.Route("files")]
[System.Web.Http.HttpPost]
[ValidateMimeMultipartContentFilter]
public async Task<FileResult> UploadSingleFile()
{
var streamProvider = new MultipartMemoryStreamProvider();
await Request.Content.ReadAsMultipartAsync(streamProvider);
string descriptionResult = string.Empty;
var description =
streamProvider.Contents.AsEnumerable()
.FirstOrDefault(T => T.Headers.ContentDisposition.Name == "\"description\"");
if (description != null)
{
descriptionResult = await description.ReadAsStringAsync();
}
return new FileResult
{
FileNames = streamProvider.Contents.AsEnumerable().Select(T => T.Headers.ContentDisposition.FileName).ToArray(),
Names = streamProvider.Contents.AsEnumerable().Select(T => T.Headers.ContentDisposition.FileName).ToArray(),
ContentTypes = streamProvider.Contents.AsEnumerable().Where(T => T.Headers.ContentType != null).Select(T => T.Headers.ContentType.MediaType).ToArray(),
Description = descriptionResult,
CreatedTimestamp = DateTime.UtcNow,
UpdatedTimestamp = DateTime.UtcNow,
};
}
}
}

Categories

Resources